import 'dart:io';

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:image_clipboard/image_clipboard.dart';
import 'package:universal_html/html.dart' as html;
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p;

// 创建全局key用于访问ScaffoldMessenger
final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey =
    GlobalKey<ScaffoldMessengerState>();

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    // 将全局key关联到MaterialApp
    return MaterialApp(
      title: '图像剪贴板示例',
      scaffoldMessengerKey: scaffoldMessengerKey, // 关键：设置全局key
      home: const HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String _platformVersion = 'Unknown';
  final _imageClipboardPlugin = ImageClipboard();
  String? _pastedImagePath;
  String? _statusMessage;

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  void setupWebPasteListener() {
    _imageClipboardPlugin
        .addWebPasteListener((html.File imageFile, String blobUrl) {
      setState(() {
        _statusMessage = '已粘贴图像: ${imageFile.name}';
        _pastedImagePath = blobUrl;
      });
      _showSnackBar(_statusMessage!);
    });
  }

  // 使用全局key显示SnackBar，彻底避免上下文问题
  void _showSnackBar(String message) {
    // 通过全局key直接访问ScaffoldMessenger
    scaffoldMessengerKey.currentState?.showSnackBar(
      SnackBar(
        content: Text(message),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  Future<void> initPlatformState() async {
    String platformVersion;
    try {
      platformVersion = await _imageClipboardPlugin.getPlatformVersion() ??
          'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    if (mounted) {
      setState(() => _platformVersion = platformVersion);
    }
  }

  Future<void> _readAndSaveImage() async {
    try {
      // 获取应用文档目录作为保存位置
      File? savedFile;
      if (Platform.isOhos) {
        // 在OHOS平台上，getFilesDir返回文件路径字符串
        savedFile = await _imageClipboardPlugin.readImageOhos();
      } else {
        Directory imageSaveDirectory = await getTemporaryDirectory();
        String path = imageSaveDirectory.path;
        final imageFileName =
            'wxx_pasted_image_${DateTime.now().millisecondsSinceEpoch}.png';

        savedFile = await _imageClipboardPlugin.readImage(
          imageSaveDirectory: path,
          imageFileName: imageFileName,
        );
      }
      setState(() {
        if (savedFile != null) {
          _pastedImagePath = savedFile.path;
          _statusMessage = '图像已保存到: ${savedFile.path}';
        } else {
          _statusMessage = '剪贴板中没有图像或保存失败';
        }
      });
      _showSnackBar(_statusMessage!);
    } catch (e) {
      _showSnackBar('读取图像失败: $e');
    }
  }

  Future<void> _copyImage() async {
    try {
      // 检查是否为OHOS平台
      if (Platform.isOhos) {
        // 读取本地assets中的图片文件为二进制数据
        final ByteData imageData =
            await rootBundle.load('assets/images/example_image.png');
        final Uint8List imageBytes = imageData.buffer.asUint8List();

        // 在OHOS平台上，使用二进制数据传递
        await _imageClipboardPlugin.copyImageOhos(imageBytes,
            mimeType: 'image/png');
        _showSnackBar('图像二进制数据已复制到剪贴板');
      } else {
        // 在其他平台上，继续使用原来的路径方式
        final imagePath = 'assets/images/example_image.png';
        await _imageClipboardPlugin.copyImage(imagePath);
        _showSnackBar('图像已复制到剪贴板');
      }
    } catch (e) {
      _showSnackBar('复制失败: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('图像剪贴板示例')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('平台版本: $_platformVersion'),
            const SizedBox(height: 20),
            if (_statusMessage != null)
              Text(_statusMessage!, style: const TextStyle(color: Colors.blue)),
            const SizedBox(height: 20),
            if (_pastedImagePath != null && _pastedImagePath!.isNotEmpty)
              Expanded(
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: Image.asset(
                    'assets/images/example_image.png'!,
                    fit: BoxFit.contain,
                    errorBuilder: (context, error, stackTrace) =>
                        const Text('无法加载图像'),
                  ),
                ),
              )
            else
              const Text('尚未粘贴图像'),
            const SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton(
                  onPressed: _copyImage,
                  child: const Text('复制示例图像'),
                ),
                const SizedBox(width: 20),
                ElevatedButton(
                  onPressed: _readAndSaveImage,
                  child: const Text('粘贴图像'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
